<?php
/**
 * @Author:      lyt
 * @DateTime:  2017-07-26 10:12:32
 * @Description: 套餐卡相关
 */
class MktServiceCardController extends BaseController {
     /**
      * @Author:      lyt
      * @DateTime:  2017-07-26 10:27:55
      * @Description: 服务卡基本信息列表 用于展示套餐卡基本信息列表
      *
      */
    public  function service_card_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "page"=>'integer',
                "page_size"=>'integer',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $page_size=Input::get("page_size",10);
            $page=Input::get("page",1);

            $scb = ServiceCardBase::leftJoin("mkt_user as mk1","mk1.id","=",'service_card_base.created_by')->leftJoin("mkt_user as mk2","mk2.id","=",'service_card_base.updated_by')->orderBy('service_card_base.created_at','desc');
            if(Input::get("user_status")!=""){ //使用状态
                $scb->where("service_card_base.user_status",Input::get("user_status"));
            }
            if(Input::get("sale_status")!=""){//销售状态
                $scb->where("service_card_base.sale_status",Input::get("sale_status"));
            }
            if(Input::get("name")!=""){//名字
                $scb->where('service_card_base.name', 'LIKE', '%'.Input::get('name').'%');
            }

            $count=$scb->count();
            $scb=$scb->skip($page_size*($page-1))->take($page_size)->select("service_card_base.*","mk1.real_name as create_name","mk2.real_name as update_name")->get();           
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("count"=>$count,"date_info"=>$scb));

        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "service_card_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
     * @Author:      lyt
     * @DateTime:  2017-07-26 15:43:13
     * @Description: 套餐卡的基本信息创建
     */
    public function service_card_create(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'name' => 'required|max:25',
                'user_status'=>'required',
                'desc' => 'max:200',
                'limit_car'=>'required',
                'limit_shop'=>'required',
                'date_type'=>'required',
                'sale_status'=>'required',
                'sale_limit'=>'required',
                'buy_number'=>'required',
                'c_sale'=>'required',
                'ids'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            if(trim(Input::get('date_type')) == 0 && (Input::get('begin_date') == "" || Input::get('end_date') == "")){
                $response = Lang::get("mkt_error.args_error_100000");
                break;
            }
            if(Input::get('date_type') == 1 && Input::get('date_num') == ""){
                $response = Lang::get("mkt_error.args_error_100000");
                break;
            }
            if(Input::get('sale_limit') == 1 && (Input::get('sale_begin_date') == "" || Input::get('sale_end_date') == "")){//金额限制 
                $response = Lang::get("mkt_error.args_error_100000");
                break;
            }            
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $findlly_array=array();
            $all_amount=0;
            //验证套餐卡服务产品
            if(Input::get('ids')){
                $moo_ids=json_decode(Input::get('ids'),1);
                foreach ($moo_ids as $_m) { 
                    $p=ProductPackage::where("id",$_m[0])->where("place",2)->where("status",1)->first();
                    if(is_null($p)){
                        $response = Lang::get("mkt_error.service_card_pack_error_95000");
                        break 2;
                    }   
                    if($_m[1]<=0){
                        $response = Lang::get("mkt_error.service_card_pack_error_95001");
                        break 2;
                    }
                    if($_m[2]<=0){
                        $response = Lang::get("mkt_error.service_card_pack_error_95002");
                        break 2;
                    }
                    if(isset($findlly_array[$_m[0]])){
                        $response = Lang::get("mkt_error.service_card_pack_error_95003");
                        break 2;
                    }
                    $findlly_array[$_m[0]]=array("id"=>$_m[0],"amount"=>$_m[1]*100,"num"=>$_m[2]);
                    $all_amount+=($_m[1]*100*$_m[2]);
                }
            }
            $scb=new ServiceCardBase();
            $scb->created_by=$mkt_user->id;
            $scb->updated_by=$mkt_user->id;
            $scb->name=Input::get("name");
            $scb->user_status=Input::get("user_status");
            $scb->desc=Input::get("desc");
            $scb->amount=$all_amount;
            $scb->limit_car=Input::get("limit_car");
            $scb->limit_shop=Input::get("limit_shop");
            $scb->date_type=Input::get("date_type");
            $scb->date_num=Input::get("date_num");
            $scb->begin_date=Input::get("begin_date")!=''?Input::get("begin_date")." 00:00:00":"0000-00-00 00:00:00";
            $scb->end_date=Input::get("end_date")!=''?Input::get("end_date")." 23:59:59":"0000-00-00 00:00:00";
            $scb->sale_status=Input::get("sale_status");
            $scb->sale_limit=Input::get("sale_limit");
            $scb->buy_number = Input::get("buy_number");
            $scb->c_sale = Input::get("c_sale",1);
            $scb->sale_begin_date=Input::get("sale_begin_date")!=''?Input::get("sale_begin_date")." 00:00:00":"0000-00-00 00:00:00";
            $scb->sale_end_date=Input::get("sale_end_date")!=''?Input::get("sale_end_date")." 23:59:59":"0000-00-00 00:00:00";
            $scb->save();
            foreach ($findlly_array as $fa) {
                $scbp=new ServiceCardBasePack();
                $scbp->service_card_base_id=$scb->id;
                $scbp->amount=$fa["amount"];
                $scbp->number=$fa["num"];
                $scbp->pack_id=$fa["id"];
                $scbp->created_by=$mkt_user->id;
                $scbp->save();
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("service_card_base_id"=>$scb->id));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "service_card_create", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-07-26 16:23:00
     * @Description: 套餐卡基本信息的车型限制信息
     *如果 要看所有的限制条件 不传 套餐卡进本信息id 即可
     */

    public function service_card_car_limit(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            //判断活动重复添加
            $check_activity_coupon = ActivityBaseInfo::where('name',Input::get('name'))->where('product_type', Input::get("product_type"))->where('status',1)->first();
            if(!is_null($check_activity_coupon)){
                $response = Lang::get("mkt_error.mkt_coupon_activity_exit_error_310002");
                break;
            }
            //获取现在 在用的车型参数
            $pc=PricingColumn::all();            
            $pct=PricingColumnType::all();
            $temp_pc=array();
            foreach ($pc as $_pc) {
                $temp_pc[$_pc->id]=$_pc;
            }


            //获取 该套餐卡的车系ing限制条件
            $scb_ck=array();
            $scbcl=ServiceCardBaseCarlimit::where("service_card_base_id",Input::get("id"))->get();
            foreach ($scbcl as $_scbcl) {
                $scb_ck[$_scbcl->pric_clo_id]=$_scbcl;
            }


            //组装返回结构
            $temp_arr=array();
            foreach ($pct as $_pct) {                
                $status=isset($scb_ck[$_pct->id])?1:0;
                if(isset($temp_arr[$_pct->col_id])){
                    $temp_arr[$_pct->col_id]["item"][]=array("id"=>$_pct->id,"name"=>$_pct->name,"status"=>$status);
                }else{                   
                    $t_pc=$temp_pc[$_pct->col_id];
                    $temp_arr[$_pct->col_id]=array("id"=>$t_pc->id,"name"=>$t_pc->name,"status"=>0,"item"=>array(array("id"=>$_pct->id,"name"=>$_pct->name,"status"=>$status)));
                }
                if($status==1){
                    $temp_arr[$_pct->col_id]["status"]=1;
                }
            }        
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("column_arr"=>array_values($temp_arr)));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "service_card_car_limit", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

   
    /**
     * @Author:      lyt
     * @DateTime:  2017-07-26 17:24:46
     * @Description: 套餐卡基本信息的车型限制信息 保存
     * 会删除现在的 套餐卡基本信息的限制信息 添加新的套餐卡基本信息车型限制
     */
    public  function service_card_car_limit_store(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "id"=>'required',
                // "limit_ids"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $scb = ServiceCardBase::find(Input::get("id"));
            if(is_null($scb)){
                $response = Lang::get("mkt_error.service_card_pack_error_95004");
                break;
            }
            //获取现在的 获取车型限制参数值
            $pct=PricingColumnType::all();
            $temp_pc=array();
            foreach ($pct as $_pct) {
                $temp_pc[$_pct->id]=$_pct;
            }
            $input = array(
                'service_card_base_id'   => $scb->id,
                'pric_clo_id'=> 0,
                'column_id' => 0,
                'created_by'      => $mkt_user->id,
                'created_at' => date('Y-m-d H:i:s',time()),
                'updated_at' => date('Y-m-d H:i:s',time()),
            );
            //验证传入的车型限制参数是否存在        
            $bag = array();
            if(Input::get('limit_ids')){
                $moo_ids=json_decode(Input::get('limit_ids'),1);
                foreach ($moo_ids as $_m) {
                    if(isset($temp_pc[$_m])){
                        $t_pct=$temp_pc[$_m];
                        $input["pric_clo_id"]=$t_pct->id;
                        $input["column_id"]=$t_pct->col_id;
                        $bag[$_m] = $input;
                    }else{
                        $response = Lang::get("mkt_error.service_card_pack_error_95005");
                        break 2;
                    }            
                }
            }
            //清除现有的 改套餐卡基本信息的车型限制
            DB::table('service_card_base_carlimit')->where("service_card_base_id",$scb->id)->delete();
            $bag=array_values($bag);
            if(sizeof($bag)>0){
                DB::table('service_card_base_carlimit')->insert($bag);
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("service_card_base_id"=>$scb->id));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "service_card_car_limit_store", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }


    /**
     * @Author:      lyt
     * @DateTime:  2017-08-07 11:06:30
     * @Description: 更改一个套餐卡基本信息
     */
    public  function service_card_update(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                "id"=>'required',
                'sale_status' => 'required',
                "user_status"=>'required',
                "c_sale"=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $scb = ServiceCardBase::find(Input::get("id"));
            if(is_null($scb)){
                $response = Lang::get("mkt_error.service_card_pack_error_95004");
                break;
            }
            $scb->sale_status=Input::get("sale_status");
            $scb->user_status=Input::get("user_status");
            $scb->c_sale=Input::get("c_sale");
            $scb->sale_begin_date=Input::get("sale_begin_date")!=''?Input::get("sale_begin_date")." 00:00:00":"0000-00-00 00:00:00";
            $scb->sale_end_date=Input::get("sale_end_date")!=''?Input::get("sale_end_date")." 23:59:59":"0000-00-00 00:00:00";
            $scb->sale_limit=Input::get("sale_limit",0);
            $scb->save();           
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("service_card_base_id"=>$scb->id));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "service_card_update", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

   

   /**
    * @Author:      lyt
    * @DateTime:  2017-07-27 11:21:08
    * @Description: 套餐卡基本信息详情页
    */
    public function service_card_show(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id'=>"required",
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{

            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }           
            $scb=ServiceCardBase::leftJoin("mkt_user as mk1","mk1.id","=",'service_card_base.created_by')->leftJoin("mkt_user as mk2","mk2.id","=",'service_card_base.updated_by')->select("service_card_base.*","mk1.real_name as create_name","mk2.real_name as update_name")->where("service_card_base.id",Input::get("id"))->first();     
            if(is_null($scb)){
                $response = Lang::get("mkt_error.service_card_pack_error_95004");
                break;
            }
            //获取服务信息    
            $scbp=ServiceCardBasePack::leftJoin("product_package","product_package.id","=","service_card_base_pack.pack_id")->where("service_card_base_pack.service_card_base_id",$scb->id)->select("service_card_base_pack.*","product_package.name")->get();

            //获取现在 在用的车型参数
            $pc=PricingColumn::all();        
            $temp_pc=array();
            foreach ($pc as $_pc) {
                $temp_pc[$_pc->id]=$_pc;
            }
            $scbcl=ServiceCardBaseCarlimit::leftJoin("pricing_column_type","pricing_column_type.id","=","service_card_base_carlimit.pric_clo_id")->where("service_card_base_carlimit.service_card_base_id",Input::get("id"))->select("service_card_base_carlimit.pric_clo_id","service_card_base_carlimit.column_id","pricing_column_type.name")->get();  
            $finall_array=array();
            foreach ($scbcl as $_scbcl) {
                if(isset($finall_array[$_scbcl->column_id])){
                    $col=array("id"=>$_scbcl->pric_clo_id,"name"=>$_scbcl->name);
                    $finall_array[$_scbcl->column_id]["item"][]=$col;
                }else{
                    $temp=$temp_pc[$_scbcl->column_id];
                    $col=array("id"=>$_scbcl->pric_clo_id,"name"=>$_scbcl->name);
                    $finall_array[$_scbcl->column_id]=array("name"=>$temp->name,"id"=>$_scbcl->column_id,"item"=>array($col));
                }
            }
            $temp_arr=array("service_card_base"=>$scb,"service_card_base_pack"=>$scbp,"car_limit"=>array_values($finall_array));
            $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "service_card_show", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    
    // /**
    //  * @Author:      lyt
    //  * @DateTime:  2017-07-27 19:01:33
    //  * @Description: 套餐的销售订单的 列表接口
    //  */
    // public function service_card_detail_list(){
    //     $validator = Validator::make(Input::all(),
    //         array(
    //             'token' => 'required',
    //             'id'=>"required",
    //         )
    //     );
    //     $response = array('code' => 0, 'msg' => 'ok');
    //     do{

    //         if($validator->fails()) {
    //             $response = Lang::get("mkt_error.args_error_100000");
    //             $response["result"]=$validator->messages()->all();
    //             break;
    //         }
    //         $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
    //         if(is_null($mkt_user)){
    //             break;
    //         }
    //         $coupon = CouponBaseInfo::where('id',Input::get('id'))->first();
    //         if(empty($coupon)){
    //             $response = Lang::get("mkt_error.coupon_not_exit_error_510001");
    //             break;
    //         }
    //         $activity_coupon_info = ActivityCouponInfo::leftjoin('activity_base_info','activity_coupon_info.activity_id','=','activity_base_info.id')
    //             ->where('activity_coupon_info.coupon_base_info_id',$coupon->id)
    //             ->where('activity_coupon_info.status',1)
    //             ->select(array('activity_base_info.name', 'activity_coupon_info.activity_id'))
    //             ->first();

    //         $coupon_received = Coupons::where('status',2)->where('coupon_base_info_id',$coupon->id)->count();
    //         $coupon_used = Coupons::where('status',4)->where('coupon_base_info_id',$coupon->id)->count();
    //         $coupon_surplus = Coupons::where('status',1)->where('coupon_base_info_id',$coupon->id)->count();
    //         $coupon_statistics = array();
    //         $coupon_statistics = array(
    //             'coupon_received' => $coupon_received,
    //             'coupon_used' => $coupon_used,
    //             'coupon_surplus' => $coupon_surplus
    //         );
    //         $product_package = ProductPackage::select('id','name')
    //             ->where('id',$coupon->pack_id)
    //             ->first();

    //         $limit_package=CouponPackLimit::leftjoin("product_package","product_package.id","=","coupon_pack_limit.pack_id")->select("product_package.id","product_package.name")->where("coupon_pack_limit.coupon_base_info_id",$coupon->id)->get();

    //         $temp_arr=array("coupon_base_info"=>$coupon,"activity_info"=>$activity_coupon_info,'coupon_statistics'=>$coupon_statistics,'product_package'=>$product_package,"limit_package"=>$limit_package);
    //         $response = array('code' => 0, 'msg' => 'ok', 'result' => $temp_arr);
    //     }while(false);
    //     Log::info("info", array("system" => "mkt" ,"event" => "coupon_show", 'input' =>Input::all() ,"output" => $response));
    //     return json_encode($response);
    // }

    /**
    * @Author:      lyt
    * @DateTime:  2017-07-27 15:51:15
    * @Description: 门店套餐卡销售订单
    */
    public function service_card_order_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'service_card_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $token = Input::get('token');
            $page_size = Input::get("page_size", 10);
            $page = Input::get("page", 1);            
            $card_no=Input::get("card_no");
            $user_id=Input::get("user_id");

            $sco=ServiceCardOrder::leftJoin("service_card_detail","service_card_detail.id","=","service_card_order.service_card_detail_id")->leftJoin("service_card_base","service_card_base.id","=","service_card_order.service_card_id")
            ->leftJoin("users","users.id","=","service_card_order.user_id")->where("service_card_order.service_card_id",Input::get("service_card_id"));
           
            if($card_no){
                $sco=$sco->where("service_card_order.service_card_detail_id","like",'%'.$card_no.'%');
            }
            if($user_id){
                $user_id_arr=Users::where("phone","like",'%'.$user_id.'%')->orWhere("real_name","like",'%'.$user_id.'%')->select("id")->get()->toArray();
                $sco=$sco->whereIn("service_card_order.user_id",$user_id_arr);
            }
            $count=$sco->count();
            $sco=$sco->skip($page_size*($page-1))->take($page_size)->select("service_card_order.*","service_card_detail.id as card_no","service_card_base.name as card_name","users.phone","users.real_name","users.type","service_card_detail.get_time","service_card_detail.end_date","service_card_detail.status as card_status")->get();
            $response = array('code' => 0, 'msg' => 'ok', 'result' =>array("count"=>$count,"orders"=>$sco));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "service_card_order_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    


   /**
    * @Author:      lyt
    * @DateTime:  2017-07-27 10:01:21
    * @Description: 套餐卡基本信息的城市配置
    */
    public  function city_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $scbc=ServiceCardBaseCity::where("service_card_base_id",Input::get('id'))->where("status",1)->get();
            $citys=array();
            foreach($scbc as $_scbc){                
                $citys[]=$_scbc->city_id;
            }

            $all_cit=DB::select("select rct.id,rct.name,rpt.id rid ,rpt.`name` p_name from resource_city_type rct LEFT JOIN resource_city rc on rc.id=rct.id
                    LEFT JOIN resource_province_type rpt on rpt.id=rc.province_id where rct.`status`=1");
            foreach ($all_cit as $_r) {
                if(isset($resource_arr[$_r->rid])){
                    $temparr=$resource_arr[$_r->rid];
                    $temparr["item"][]=$_r;
                    $resource_arr[$_r->rid]=$temparr;
                }else{
                    $resource_arr[$_r->rid]=array(
                        'r_id'=>$_r->rid,
                        'name'=>$_r->p_name,
                        'item'=>array($_r),
                    );
                }
            }
            $resource_arr=array_values($resource_arr);
            foreach($resource_arr as $ra){
                foreach($ra['item'] as $item){
                    if(in_array($item->id,$citys)){
                        $item->status=1;
                    }else{
                        $item->status=0;
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('city_list'=>$resource_arr));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "city_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
   /**
    * @Author:      lyt
    * @DateTime:  2017-07-27 10:01:21
    * @Description: 套餐卡使用基本信息的城市配置
    */
    public  function city_list_use(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $scbc=ServiceCardBaseCityUse::where("service_card_base_id",Input::get('id'))->where("status",1)->get();
            $citys=array();
            foreach($scbc as $_scbc){                
                $citys[]=$_scbc->city_id;
            }

            $all_cit=DB::select("select rct.id,rct.name,rpt.id rid ,rpt.`name` p_name from resource_city_type rct LEFT JOIN resource_city rc on rc.id=rct.id
                    LEFT JOIN resource_province_type rpt on rpt.id=rc.province_id where rct.`status`=1");
            foreach ($all_cit as $_r) {
                if(isset($resource_arr[$_r->rid])){
                    $temparr=$resource_arr[$_r->rid];
                    $temparr["item"][]=$_r;
                    $resource_arr[$_r->rid]=$temparr;
                }else{
                    $resource_arr[$_r->rid]=array(
                        'r_id'=>$_r->rid,
                        'name'=>$_r->p_name,
                        'item'=>array($_r),
                    );
                }
            }
            $resource_arr=array_values($resource_arr);
            foreach($resource_arr as $ra){
                foreach($ra['item'] as $item){
                    if(in_array($item->id,$citys)){
                        $item->status=1;
                    }else{
                        $item->status=0;
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array('city_list'=>$resource_arr));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "city_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
    * @Author:      lyt
    * @DateTime:  2017-07-27 10:17:22
    * @Description: 套餐卡的城市配置
    */
    public function save_citys(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'city_ids'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $city_ids=json_decode(Input::get('city_ids'));
            ServiceCardBaseCity::where("service_card_base_id",Input::get('id'))->where("status",1)->update(array('status'=>0));
            foreach ($city_ids as $_c) {
                $pas=new ServiceCardBaseCity();
                $pas->service_card_base_id = Input::get('id');
                $pas->city_id = $_c;
                $pas->created_by = $mkt_user->id;
                $pas->status =1;
                $pas->save();
            }
/**
 * 修改城市适配的时候，不修改当前城市下所有门店  20170925 赵洋
 */
//            $ms=MaintenanceShops::whereIn('city_id',$city_ids)->where('status',1)->get();
            ServiceCardBaseShop::where('service_card_base_id',Input::get('id'))->where('status',1)->update(array('status'=>0));
//            foreach($ms as $_ms){
//                $pas=new ServiceCardBaseShop();
//                $pas->service_card_base_id = Input::get('id');
//                $pas->shop_id = $_ms->id;
//                $pas->created_by = $mkt_user->id;
//                $pas->status =1;
//                $pas->save();
//            }
    
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("id"=>Input::get('id')));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "save_citys", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    /**
    * @Author:      lyt
    * @DateTime:  2017-07-27 10:17:22
    * @Description: 套餐卡使用的城市配置
    */
    public function save_citys_use(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'city_ids'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $city_ids=json_decode(Input::get('city_ids'));
            ServiceCardBaseCityUse::where("service_card_base_id",Input::get('id'))->where("status",1)->update(array('status'=>0));
            foreach ($city_ids as $_c) {
                $pas=new ServiceCardBaseCityUse();
                $pas->service_card_base_id = Input::get('id');
                $pas->city_id = $_c;
                $pas->created_by = $mkt_user->id;
                $pas->status =1;
                $pas->save();
            }
/**
 * 修改城市适配的时候，不修改当前城市下所有门店  20170925 赵洋
 */
//            $ms=MaintenanceShops::whereIn('city_id',$city_ids)->where('status',1)->get();
            ServiceCardBaseShopUse::where('service_card_base_id',Input::get('id'))->where('status',1)->update(array('status'=>0));
//            foreach($ms as $_ms){
//                $pas=new ServiceCardBaseShopUse();
//                $pas->service_card_base_id = Input::get('id');
//                $pas->shop_id = $_ms->id;
//                $pas->created_by = $mkt_user->id;
//                $pas->status =1;
//                $pas->save();
//            }
    
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("id"=>Input::get('id')));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "save_citys", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
     /**
      * @Author:      lyt
      * @DateTime:  2017-07-27 10:30:39
      * @Description: 套餐卡城市
      */
    public  function shop_list(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            
            $pas=ServiceCardBaseCity::where("service_card_base_id",Input::get('id'))->where("status",1)->get();            
            $shop_ids=ServiceCardBaseShop::where('service_card_base_id',Input::get('id'))->where('status',1)->select("shop_id")->get()->toArray();
            $shop_ids=array_column($shop_ids,'shop_id');
            $citys=array();
            foreach($pas as $_pas){
                $ms=MaintenanceShops::leftJoin("resource_region","resource_region.id","=","maintenance_shops.region_id")->where('maintenance_shops.city_id',$_pas->city_id)->where('maintenance_shops.status',1)->select('maintenance_shops.id','maintenance_shops.name',"resource_region.region_name")->get();
                $citys[]=array('id'=>$_pas->city_id,'item'=>$ms);
            }
            foreach($citys as $key=>$city){
                $cc=CommonCity::find($city['id']);
                $citys[$key]['name']=$cc->name;
                foreach($city['item'] as $item){
                    if(in_array($item->id,$shop_ids)){
                        $item->status=1;
                    }else{
                        $item->status=0;
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("shop_info"=>$citys));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "shop_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
   
     /**
      * @Author:      lyt
      * @DateTime:  2017-07-27 10:30:39
      * @Description: 套餐卡使用城市
      */
    public  function shop_list_use(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required'
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("scs_error.args_error_10000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            
            $pas=  ServiceCardBaseCityUse::where("service_card_base_id",Input::get('id'))->where("status",1)->get();            
            $shop_ids=  ServiceCardBaseShopUse::where('service_card_base_id',Input::get('id'))->where('status',1)->select("shop_id")->get()->toArray();
            $shop_ids=array_column($shop_ids,'shop_id');
            $citys=array();
            foreach($pas as $_pas){
                $ms=MaintenanceShops::leftJoin("resource_region","resource_region.id","=","maintenance_shops.region_id")->where('maintenance_shops.city_id',$_pas->city_id)->where('maintenance_shops.status',1)->select('maintenance_shops.id','maintenance_shops.name',"resource_region.region_name")->get();
                $citys[]=array('id'=>$_pas->city_id,'item'=>$ms);
            }
            foreach($citys as $key=>$city){
                $cc=CommonCity::find($city['id']);
                $citys[$key]['name']=$cc->name;
                foreach($city['item'] as $item){
                    if(in_array($item->id,$shop_ids)){
                        $item->status=1;
                    }else{
                        $item->status=0;
                    }
                }
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("shop_info"=>$citys));
        }while(false);
        Log::info("info", array("system" => "scs" ,"event" => "shop_list", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    
    
    /**
     * @Author:      lyt
     * @DateTime:  2017-07-27 10:39:19
     * @Description: 套餐卡使用门店信息保存
     */
    public function save_shops_use(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'shop_ids'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;            
            }
            $shop_ids=json_decode(Input::get('shop_ids'),1);
            ServiceCardBaseShopUse::where('service_card_base_id',Input::get('id'))->where('status',1)->update(array('status'=>0));
            foreach($shop_ids as $shop_id){                
                $pas=new ServiceCardBaseShopUse();
                $pas->service_card_base_id = Input::get('id');
                $pas->shop_id = $shop_id;
                $pas->created_by = $mkt_user->id;
                $pas->status =1;
                $pas->save();
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("id"=>Input::get('id')));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "save_shops", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }

    /**
     * @Author:      lyt
     * @DateTime:  2017-07-27 10:39:19
     * @Description: 套餐卡门店信息保存
     */
    public function save_shops(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'id' => 'required',
                'shop_ids'=>'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;            
            }
            $shop_ids=json_decode(Input::get('shop_ids'),1);
            ServiceCardBaseShop::where('service_card_base_id',Input::get('id'))->where('status',1)->update(array('status'=>0));
            foreach($shop_ids as $shop_id){                
                $pas=new ServiceCardBaseShop();
                $pas->service_card_base_id = Input::get('id');
                $pas->shop_id = $shop_id;
                $pas->created_by = $mkt_user->id;
                $pas->status =1;
                $pas->save();
            }
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("id"=>Input::get('id')));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "save_shops", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
    

    /**
     * @Author:      lyt
     * @DateTime:  2017-08-07 14:09:28
     * @Description: 统计套餐卡的统计
     */
    public function statistics(){
        $validator = Validator::make(Input::all(),
            array(
                'token' => 'required',
                'service_card_id' => 'required',
            )
        );
        $response = array('code' => 0, 'msg' => 'ok');
        do{
            if($validator->fails()) {
                $response = Lang::get("mkt_error.args_error_100000");
                $response["result"]=$validator->messages()->all();
                break;
            }
            $mkt_user=$this->verificationMKTUserToken(Input::get("token"),$response);
            if(is_null($mkt_user)){
                break;
            }
            $start=date('Y-m-d 00:00:00',time());
            $end=date('Y-m-d 23:59:59',time());

            //门店模糊搜索
            $ms_ids=array();
            // if(Input::get('shop_name')!=""){
            //     $ms_ids=MaintenanceShops::where('name','like','%'.Input::get('shop_name').'%')->select('id')->get()->toArray();
            //     $ms_ids=array_column($ms_ids,'id');
            // }     

            if(Input::get('shop_id')!=""){
                $ms_ids[]=Input::get('shop_id');
            }        
            $all_sco=ServiceCardOrder::leftJoin('maintenance_shops','maintenance_shops.id','=','service_card_order.shop_id'); 
            if(Input::get('shop_id')!=""){
                $all_sco=$all_sco->whereIn('service_card_order.shop_id',$ms_ids);
            }
            if(Input::get('city_id')!=""){
                $all_sco=$all_sco->where('maintenance_shops.city_id',Input::get('city_id'));
            }
            $all_sco=$all_sco->whereIn('service_card_order.status',Orders::$complete)->where('service_card_order.service_card_id',Input::get('service_card_id'));
            $temp_sco=$all_sco->select('shop_id')->get()->toArray();
            $shop_ids=array_column($temp_sco,'shop_id');
            $shop_ids=array_unique($shop_ids);
            sort($shop_ids);
            
            $statistics=array();

            $statistics['sum_shop_num']=count($shop_ids);    //总门店数   
            $city_ids=MaintenanceShops::whereIn('id',$shop_ids)->select('city_id')->distinct('city_id')->get();
            $statistics['sum_city_num']=count($city_ids);    //总城市数
            //总销量 总收益           
            $sales_num=$all_sco->count();
            $sales_amount=$all_sco->sum('service_card_order.pay_amount');
            $statistics['sum_sales_num']=$sales_num;
            $statistics['sum_sales_amount']=($sales_amount)/100;
       
            

            $statistics_detail=array();
            //各个门店销量及收益情况
            foreach($shop_ids as $shop_id){
                $shop=array();
                $shop['shop_id']=$shop_id;
                $ms=MaintenanceShops::find($shop_id);
                $shop['shop_name']=$ms->name;
                $cc=CommonCity::find($ms->city_id);
                $shop['city_id']=$ms->city_id;
                $shop['city_name']=$cc->name;
                //当前门店总收益
                $shop_sco=ServiceCardOrder::where("shop_id",$shop_id)->whereIn('status',Orders::$complete)->where('service_card_id',Input::get('service_card_id'));
                $sale_amount=$shop_sco->sum('pay_amount');                
                $shop['sale_amount']=($sale_amount)/100;
                //当前门店总销量
                $sale_num=$shop_sco->count();
                $shop['sale_num']=$sale_num;
                //当前门店今日总收益
                $sale_amount_today=$shop_sco->where('pay_time','>=',$start)->where('pay_time','<=',$end)->sum('pay_amount');                
                $shop['sale_amount_today']=($sale_amount_today)/100;
               //当前门店今日总销量
                $sale_num_today=$shop_sco->where('pay_time','>=',$start)->where('pay_time','<=',$end)->count();
                $shop['sale_num_today']=$sale_num_today;
                $statistics_detail[]=$shop;
            }   

            //城市搜索
            if(Input::get('sort')!="" && sizeof($statistics_detail)>0){
                if(Input::get('sort')==1){//总销量降序
                    foreach($statistics_detail as $key=>$sd){
                        $arr[$key]=$sd['sale_num'];
                    }
                    array_multisort($arr, SORT_DESC,$statistics_detail);
                }
                if(Input::get('sort')==2){//总销量升序
                    foreach($statistics_detail as $key=>$sd){
                        $arr[$key]=$sd['sale_num'];
                    }
                    array_multisort($arr, SORT_ASC,$statistics_detail);
                }
                if(Input::get('sort')==3){//今日销量降序
                    foreach($statistics_detail as $key=>$sd){
                        $arr[$key]=$sd['sale_num_today'];
                    }
                    array_multisort($arr, SORT_DESC,$statistics_detail);
            
                }
                if(Input::get('sort')==4){//今日销量升序
                    foreach($statistics_detail as $key=>$sd){
                        $arr[$key]=$sd['sale_num_today'];
                    }
                    array_multisort($arr, SORT_ASC,$statistics_detail);
                }
            }
            $sum_sale_num_today=0;
            $sum_sale_amount_today=0;
            foreach($statistics_detail as $_sd){
                $sum_sale_amount_today+=$_sd['sale_amount_today'];
                $sum_sale_num_today+=$_sd['sale_num_today'];
            }
            
            $statistics['sum_sale_amount_today']=$sum_sale_amount_today;
            $statistics['sum_sale_num_today']=$sum_sale_num_today;
            
            $response = array('code' => 0, 'msg' => 'ok', 'result' => array("statistics"=>$statistics,"statistics_detail"=>$statistics_detail));
        }while(false);
        Log::info("info", array("system" => "mkt" ,"event" => "statistics", 'input' =>Input::all() ,"output" => $response));
        return json_encode($response);
    }
}